<template>
  <div class="video-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <div class="breadcrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/industry-belt' }">产业带</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/industry-belt', query: { tab: 'video' } }">行业视频</el-breadcrumb-item>
            <el-breadcrumb-item>{{ videoData?.title || '视频详情' }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </div>
    </div>

    <!-- 视频内容 -->
    <div class="video-content" v-if="!loading && videoData">
      <div class="container">
        <div class="video-main">
          <!-- 视频信息 -->
          <div class="video-info">
            <h1 class="video-title">{{ videoData.title }}</h1>

            <!-- 元信息 -->
            <div class="video-meta">
              <div class="meta-left">
                <span class="date">
                  <el-icon class="date-icon"><Calendar /></el-icon> {{ formatDate(videoData.publishDate) }}
                </span>
                <span class="duration" v-if="videoData.durationMinutes">
                  <el-icon class="duration-icon"><Clock /></el-icon> {{ formatDuration(videoData.durationMinutes) }}
                </span>
              </div>
              <div class="meta-right">
                <span class="views">
                  <el-icon><View /></el-icon> {{ videoData.views || 0 }} 观看
                </span>
                <span class="likes">
                  <el-icon><Star /></el-icon> {{ videoData.likes || 0 }} 点赞
                </span>
                <span class="collects">
                  <el-icon><Collection /></el-icon> {{ videoData.collects || 0 }} 收藏
                </span>
              </div>
            </div>
          </div>

          <!-- 视频播放器 -->
          <div class="video-player-container">
            <!-- <div class="back-action" style="margin-bottom: 12px;">
              <el-button @click="() => navigateTo('/industry-belt?tab=video')">返回列表</el-button>
            </div> -->
            <div class="video-player">
              <video
                v-if="videoUrl"
                :src="videoUrl"
                controls
                preload="metadata"
                class="video-element"
                @loadstart="handleVideoLoadStart"
                @canplay="handleVideoCanPlay"
                @error="handleVideoError"
                @play="handleVideoPlay"
                @pause="handleVideoPause"
                @ended="handleVideoEnded"
              >
                您的浏览器不支持视频播放。
              </video>
              <div v-else class="video-placeholder">
                <el-icon class="play-icon"><VideoPlay /></el-icon>
                <p>视频加载中...</p>
              </div>
            </div>
          </div>

          <!-- 视频描述和标签 -->
          <div class="video-details">
            <!-- 视频描述 -->
            <div class="video-description" v-if="videoData.summary">
              <h3>视频简介</h3>
              <p>{{ videoData.summary }}</p>
            </div>

            <!-- 标签 -->
            <div class="video-tags" v-if="videoData.tags && videoData.tags.length > 0">
              <h3>标签</h3>
              <div class="tags-list">
                <span v-for="tag in videoData.tags" :key="tag.id" class="tag">{{ tag.tagName }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 侧边栏 -->
        <div class="video-sidebar">
          <!-- 相关视频 -->
          <div class="related-videos">
            <h3>相关视频</h3>
            <div class="related-list">
              <div
                v-for="item in relatedVideos"
                :key="(item as any).id"
                class="related-item"
                @click="goToVideo((item as any).id)"
              >
                <div class="related-thumbnail">
                  <img :src="(item as any).coverImageUrl" />
                  <div class="duration-tag">{{ formatDuration((item as any).durationMinutes) }}</div>
                </div>
                <div class="related-info">
                  <h4>{{ (item as any).title }}</h4>
                  <span class="related-date">{{ formatDate((item as any).publishDate) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="视频不存在或已被删除">
        <el-button type="primary" @click="() => navigateTo('/industry-belt?tab=video')">返回列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { Calendar, Clock, View, Star, Collection, VideoPlay } from '@element-plus/icons-vue'
import { industryBeltApi } from '~/server/industryBeltApi'
import { ElMessage } from 'element-plus'
import { formatDuration, parseDurationToMinutes } from '~/utils/duration'

// 获取路由参数
const route = useRoute()
const videoId = route.params.id as string

// 响应式数据
const loading = ref(true)
const videoData = ref<any>(null)
const relatedVideos = ref<any[]>([])
const videoUrl = ref('')

// 视频播放状态
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化时长由统一工具提供（分钟可含小数，显示到秒）

// 清洗URL
const normalizeUrl = (url: any): string => {
  if (!url) return ''
  if (typeof url !== 'string') return ''
  return url.replace(/[`]/g, '').trim()
}

// 解析时长由统一工具提供（保留秒，返回分钟小数）

// 标签数组化
const toTagArray = (tags: any): Array<{ id: number; tagName: string; status: any; createTime: any }> => {
  if (Array.isArray(tags)) return tags
  if (typeof tags === 'string' && tags.trim()) {
    return tags
      .split(',')
      .map((t: string, i: number) => ({ id: i + 1, tagName: t.trim(), status: undefined, createTime: undefined }))
  }
  return []
}

// 映射会议视频结构
const mapConferenceVideo = (raw: any) => ({
  id: raw?.id ?? 0,
  title: raw?.title ?? '',
  summary: raw?.news ?? raw?.description ?? '',
  durationMinutes: parseDurationToMinutes(raw?.videoDuration ?? 0),
  publishDate: raw?.conferenceDate ?? raw?.updateTime ?? '',
  coverImageUrl: normalizeUrl(raw?.videoThumbnailUrl ?? raw?.coverImageUrl),
  videoUrl: normalizeUrl(raw?.videoUrl ?? ''),
  views: 0,
  likes: 0,
  collects: 0,
  tags: toTagArray(raw?.tags),
})

// 获取视频详情（基于会议视频列表匹配当前ID）
const fetchVideoDetail = async () => {
  try {
    loading.value = true
    const response = await industryBeltApi.content.getList({ contentType: 'VIDEO', pageNum: 1, pageSize: 200 })
    const list = Array.isArray(response?.list) ? response.list : []
    const found = list.find((item: any) => item.id === Number(videoId))
    if (found) {
      const mapped = mapConferenceVideo(found)
      videoData.value = mapped
      videoUrl.value = mapped.videoUrl
    } else {
      videoData.value = null
      videoUrl.value = ''
    }
  } catch (error) {
    console.error('获取视频详情失败:', error)
    const errorMessage = error?.toString() || ''
    if (errorMessage.includes('401') || errorMessage.includes('402') || errorMessage.includes('登录')) {
      ElMessage.warning('请先登录后再查看视频详情')
    } else {
      ElMessage.error('获取视频详情失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 获取相关视频（映射为统一结构）
const fetchRelatedVideos = async () => {
  try {
    const response = await industryBeltApi.content.getList({ contentType: 'VIDEO', pageNum: 1, pageSize: 20 })
    const list = Array.isArray(response?.list) ? response.list : []
    relatedVideos.value = list
      .filter((item: any) => item.id !== Number(videoId))
      .slice(0, 5)
      .map((item: any) => mapConferenceVideo(item))
  } catch (error) {
    console.error('获取相关视频失败:', error)
    const errorMessage = error?.toString() || ''
    if (errorMessage.includes('401') || errorMessage.includes('402') || errorMessage.includes('登录')) {
      console.warn('相关视频需要登录才能查看')
    }
  }
}

// 跳转到其他视频
const goToVideo = (id: any) => {
  navigateTo(`/industry-belt/video/${id}`)
}

// 视频事件处理
const handleVideoLoadStart = () => {
  console.log('视频开始加载')
}

const handleVideoCanPlay = () => {
  console.log('视频可以播放')
}

const handleVideoError = (event: any) => {
  console.error('视频加载失败:', event)
  ElMessage.error('视频加载失败，请稍后重试')
}

const handleVideoPlay = () => {
  isPlaying.value = true
}

const handleVideoPause = () => {
  isPlaying.value = false
}

const handleVideoEnded = () => {
  isPlaying.value = false
  ElMessage.success('视频播放完成')
}

// 页面加载时获取数据
onMounted(() => {
  fetchVideoDetail()
  fetchRelatedVideos()
})

// 页面卸载时清理
onUnmounted(() => {
  // 清理视频资源
  videoUrl.value = ''
})

// SEO优化
useHead({
  title: computed(() => videoData.value?.title || '视频详情'),
  meta: [
    {
      name: 'description',
      content: computed(() => videoData.value?.summary || ''),
    },
  ],
})
</script>

<style scoped lang="scss">
.video-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px 0;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .breadcrumb {
    width: 100%;
  }
}

.video-content {
  padding: 30px 0;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 30px;
  }
}

.video-main {
  background: #fff;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.video-details {
  padding: 30px;

  .video-description {
    margin-bottom: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    border-left: 4px solid #e93323;

    h3 {
      margin: 0 0 15px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: #666;
      font-size: 16px;
      line-height: 1.6;
    }
  }

  .video-tags {
    margin-bottom: 30px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;

    h3 {
      margin: 0 0 15px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    .tags-list {
      .tag {
        display: inline-block;
        background: #f0f9ff;
        color: #1890ff;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 14px;
        margin-right: 10px;
        margin-bottom: 10px;
      }
    }
  }
}

.video-player-container {
  position: relative;
  width: 100%;
  background: #000;
  border-radius: 8px 8px 0 0;
  overflow: hidden;

  .video-player {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%; // 16:9 宽高比

    .video-element {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      background: #000;
    }

    .video-placeholder {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: #000;
      color: #fff;

      .play-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.7;
      }

      p {
        margin: 0;
        font-size: 16px;
        opacity: 0.7;
      }
    }
  }
}

.video-info {
  padding: 30px;
  border-bottom: 1px solid #e4e7ed;

  .video-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 20px 0;
    line-height: 1.4;
  }

  .video-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;

    .meta-left {
      display: flex;
      gap: 20px;
      align-items: center;

      .date,
      .duration {
        display: flex;
        align-items: center;
        color: #999;
        font-size: 14px;

        .date-icon,
        .duration-icon {
          color: #e93323;
          margin-right: 4px;
        }
      }
    }

    .meta-right {
      display: flex;
      gap: 20px;
      align-items: center;

      span {
        display: flex;
        align-items: center;
        color: #666;
        font-size: 14px;

        .el-icon {
          margin-right: 4px;
          color: #999;
        }
      }
    }
  }
}

.video-sidebar {
  .related-videos {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0 0 20px 0;
      color: #333;
      font-size: 18px;
      font-weight: 600;
    }

    .related-list {
      .related-item {
        display: flex;
        gap: 12px;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: all 0.3s ease;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          background: #f8f9fa;
          border-radius: 4px;
          padding-left: 8px;
        }

        .related-thumbnail {
          position: relative;
          width: 80px;
          height: 60px;
          flex-shrink: 0;
          border-radius: 4px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .duration-tag {
            position: absolute;
            bottom: 4px;
            right: 4px;
            background: rgba(0, 0, 0, 0.7);
            color: #fff;
            padding: 2px 6px;
            border-radius: 2px;
            font-size: 10px;
          }
        }

        .related-info {
          flex: 1;
          min-width: 0;

          h4 {
            margin: 0 0 8px 0;
            color: #333;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.4;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }

          .related-date {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.loading-container,
.error-container {
  max-width: 1200px;
  margin: 50px auto;
  padding: 0 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .video-content .container {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .video-main {
    .video-info {
      padding: 20px;

      .video-title {
        font-size: 20px;
      }

      .video-meta {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;

        .meta-left {
          flex-wrap: wrap;
          gap: 15px;
        }

        .meta-right {
          flex-wrap: wrap;
          gap: 15px;
        }
      }
    }
  }

  .video-sidebar {
    order: -1;

    .related-videos {
      .related-list {
        .related-item {
          .related-thumbnail {
            width: 60px;
            height: 45px;
          }
        }
      }
    }
  }
}

// 视频播放器全屏样式
@media (max-width: 480px) {
  .video-player-container {
    .video-player {
      padding-bottom: 60%; // 调整移动端宽高比
    }
  }
}
</style>
